﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ComicTracker.Models;

namespace ComicTracker.Controllers
{
    public class IssueController : Controller
    {
        ComicTrackerContext db = new ComicTrackerContext();

        public ActionResult Details(Guid id)
        {
            Session["lastPage"] = Request.Url.ToString();
            var issue = db.Issues.Find(id);
            return View(issue);
        }

        public ActionResult Create(Guid? seriesID = null)
        {
            if (seriesID != null)
                ViewBag.SeriesID = new SelectList(db.Series, "ID", "Name",
                    seriesID.Value);
            else
                ViewBag.SeriesID = new SelectList(db.Series, "ID", "Name");
            ViewBag.LastPage = Session["lastPage"].ToString();
            return View();
        }

        [HttpPost]
        public ActionResult Create(Issue issue)
        {
            if (ModelState.IsValid)
            {
                issue.ID = Guid.NewGuid();
                db.Issues.Add(issue);
                db.SaveChanges();

                string redirect = Session["lastPage"].ToString();
                return Redirect(redirect);
            }

            ViewBag.SeriesID = new SelectList(db.Series, "ID", "Name", issue.SeriesID);
            return View(issue);
        }

        public ActionResult Edit(Guid id)
        {
            var issue = db.Issues.Find(id);
            ViewBag.SeriesID = new SelectList(db.Series, "ID", "Name", issue.SeriesID);
            return View(issue);
        }

        [HttpPost]
        public ActionResult Edit(Issue issue)
        {
            if (ModelState.IsValid)
            {
                db.Entry(issue).State = System.Data.EntityState.Modified;
                db.SaveChanges();
                return Redirect(Session["lastPage"].ToString());
            }
            return View(issue);
        }
    }
}
